// pages/comments/comments.js
const app = getApp()
const ajax = require('../../utils/ajax.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    topList: [
      "写评论",
      "看评价"
    ],
    buyorno:"",
    evaluateorno:"",
    bechoice: "0",
    goodPic:"",
    goodName:"",
    commentsList:[],
    tempFilePaths: [],
    images: [],
    num: 0,
    text_num: 0,
    beater: 0,
    imgid: [],
    content: '',
    urlimg: "",
    order_id: '',
    urlTemp:[],
    idTemp:[]
  },

  topChoice(e) {
    this.setData({
      bechoice: e.currentTarget.dataset.index
    })
  },
  uploadImg: function() {
    let that = this;
    if (that.data.beater < 3) {
      let temp = that.data.tempFilePaths;
      wx.chooseImage({
        count: 3,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          const images = res.tempFilePaths
          let urlimg = temp.concat(res.tempFilePaths)
          let filePath = res.tempFilePaths
          that.setData({
            tempFilePaths: urlimg,
           
            urlimg: urlimg
          })
          console.log('666', filePath)
          wx.showLoading({
            title: '上传中，请稍等',
            mask: true,
            duration: 60000
          })
          let urlTemp = []
          let idTemp=[]
          //上传到素材库
          for (let i = 0; i < filePath.length;i++){
            wx.uploadFile({
              url: app.urlData.getURL + '/index.php/Api/SApi/index/key/' + app.urlData.key + '/m/uploadfile/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
              filePath: filePath[i],
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                'file': filePath[i]
              },
              success: function (res) {
                wx.hideLoading();
                console.log("图片上传修改")
                console.log(res)
                let datas_img = JSON.parse(res.data)
                console.log(datas_img)

                let piclist = that.data.urlTemp.concat(datas_img.file)
                let picid = that.data.idTemp.concat(datas_img.imgid)
                console.log(picid)
                that.setData({
                  urlTemp: piclist,
                  idTemp: picid,
                  num: piclist.length,
                  beater: piclist.length,
                })
              }
            })
          }
          
        }
      })
    } else {
      wx.showToast({
        title: '最多可上传3张',
        icon: 'none'
      })
    }
  },
  //计算已输入的标题字数
  bindTextAreaBlur(e) {
    this.setData({
      text_num: e.detail.value.length,
      content: e.detail.value
    })
    if (e.detail.value.length >= 100) {
      wx.showToast({
        title: '字数已达上限',
        icon: 'none'
      })
    }
  },
  submit: function() {
    let that = this;
    let content = that.data.content;
    let order_id = that.data.order_id;
   if(that.data.content == ""){
     wx.showToast({
       title: '评论内容不能为空',
       duration:1600,
       icon:"none"
     })
     return false
   }
   if(that.data.idTemp.length == 0){
     wx.showToast({
       title: '请上传图片',
       duration:1600,
       icon:"none"
     })
     return false
   }
    let idArr = that.data.idTemp.join(",")
    console.log(idArr)
    wx.request({
      url: app.urlData.getURL + '/index.php/Api/SApi/index/key/' + app.urlData.key + '/m/addComment/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign'),
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },

      data: {
        goods_id: order_id,
        content: content,
        img_ids: idArr
      },
      success: function (res) {
        console.log(res)
        if (res.data.status == 1) {
          wx.showToast({
            title: '提交成功！',
            icon: "success",
            duration: 1600
          })
          setTimeout(function () {
            wx.navigateBack({})
          }, 2000)
        } 
        
      }
    })
  },

  choos_image: function(e) {
    let index=e.currentTarget.dataset.index
    let temp = this.data.urlTemp
    temp.splice(index, 1);
    this.data.idTemp.splice(index, 1);
    this.setData({
      urlTemp: temp,
      beater: temp.length,
      num:temp.length
    })
   

  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  preview(e){
    let that =this

    let temp = []
    for (let i = 0; i < that.data.commentsList[e.currentTarget.dataset.evaluateindex].urls.length;i++){
      temp.push(that.data.commentsList[e.currentTarget.dataset.evaluateindex].urls[i].url)
    }
    wx.previewImage({
      current: that.data.commentsList[e.currentTarget.dataset.evaluateindex].urls[e.currentTarget.dataset.picindex].url, // 当前显示图片的http链接
      urls: temp // 需要预览的图片http链接列表
    })
  },
  onLoad: function(options) {
    let that = this
    let order_id = options.id;
    that.setData({
      order_id: order_id
    })
    that.fetchGoodsDetail({
      goods_id: order_id
    })

    that.getCommentList()
    
  },
  getCommentList(){
    let that = this
    wx.request({
      url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/getCommentList/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign') + '/len/10' + '/goods_id/' + that.data.order_id + '/start/' + 0,
      method: "get",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (res) => {
        console.log(res)
        that.setData({
          commentsList: res.data.data,
          page: res.data.data.length,
          buyorno:res.data.mark
        })
        if (res.data.data.length == 0){
          that.setData({
            evaluateorno:false
          })
        }else{
          that.setData({
            evaluateorno: true
          })
        }
        console.log(that.data.buyorno)
      }
    })
  },

  fetchGoodsDetail(obj) {
    ajax
      .wxRequest({
        url: '/index.php/api/SApi/index/m/getPageGoodsInfo/',
        data: typeof obj === 'object' ? obj : {}
      })
      .then(res => {
        if(res.status == 1){
          this.setData({
            goodPic: res.datas.goods.original_img,
            goodName: res.datas.goods.goods_name,
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    console.log("000")
    var that = this
    // if (that.data.loading == true) {
    var page = that.data.page
    wx.request({
      url: app.urlData.getURL + '/index.php/api/SApi/index/key/' + app.urlData.key + '/m/getCommentList/wid/' + app.urlData.wid + '/sign/' + wx.getStorageSync('sign') + '/len/10' + '/goods_id/' + that.data.goods_id + '/start/' + that.data.page,

      method: "get",
      data: {
        start: page,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (res) => {
        console.log(res)
        if (res.data.data != '') {
          that.setData({
            commentsList: that.data.commentsList.concat(res.data.data),
            page: that.data.page + res.data.data.length,
            loadingItem: 1
          })
        } else {
          that.setData({
            commentsList: that.data.commentsList.concat(res.data.data),
            loadingItem: 1,
            loading: false
          })
        }
      }
    })
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})